import pandas as pd
from datetime import date, timedelta

import sys


def __get_sale_num(df_row_selected):
    # last_sale_num
    global las_sale_num
    for idx, row in df_row_selected.iterrows():
        las_sale_num = row['销售数量']
        break

    # print('last sale num:', las_sale_num)
    return las_sale_num


def calc_history_data(m_sale_data):
    history_sale = pd.DataFrame(
        columns=['日期', 'sale_num', 'last_day', 'last_2day', 'last_3day', 'last_7day'])
    history_sale.astype({'日期': str})
    for index, row in m_sale_data.iterrows():
        curr_date = date.fromisoformat(row['日期'])
        last_day = curr_date - timedelta(days=1)
        last_2day = curr_date - timedelta(days=2)
        last_3day = curr_date - timedelta(days=3)
        last_7day = curr_date - timedelta(days=7)

        selected_row1 = m_sale_data[m_sale_data['日期']
                                    == last_day.strftime("%Y-%m-%d")]
        selected_row2 = m_sale_data[m_sale_data['日期']
                                    == last_2day.strftime("%Y-%m-%d")]
        selected_row3 = m_sale_data[m_sale_data['日期']
                                    == last_3day.strftime("%Y-%m-%d")]
        selected_row7 = m_sale_data[m_sale_data['日期']
                                    == last_7day.strftime("%Y-%m-%d")]

        sale_last_day = row['销售数量']
        sale_last_2day = row['销售数量']
        sale_last_3day = row['销售数量']
        sale_last_7day = row['销售数量']

        if not selected_row1.empty:
            sale_last_day = __get_sale_num(selected_row1)
            # m_sale_data.loc[index, 'last_day'] = sale_last_day
        if not selected_row2.empty:
            sale_last_2day = __get_sale_num(selected_row2)
            # m_sale_data.loc[index, 'last_2day'] = sale_last_2day

        if not selected_row3.empty:
            sale_last_3day = __get_sale_num(selected_row3)
            # m_sale_data.loc[index, 'last_3day'] = sale_last_3day

        if not selected_row7.empty:
            sale_last_7day = __get_sale_num(selected_row7)
            # m_sale_data.loc[index, 'last_7day'] = sale_last_7day
        history_sale = history_sale.append(
            {'日期': curr_date, 'sale_num': row['销售数量'], 'last_day': sale_last_day, 'last_2day': sale_last_2day,
             'last_3day': sale_last_3day,
             'last_7day': sale_last_7day}, ignore_index=True)

    history_sale = history_sale.drop(columns='sale_num')
    # print("cacl history data:", history_sale)

    return history_sale


init_date = date.fromisoformat('2017-12-24')
sale_data = pd.read_csv('./data/001488.csv', dtype={'日期': str, '商品编码': str})
# print(sale_data)
sale_data_processed1 = sale_data.iloc[:, 0:7]

sale_data_processed1['出行方便'] = sale_data_processed1.apply(lambda r: 0 if '雨' in r['天气'] or '雪' in r['天气'] else 1,
                                                          axis=1)
sale_data_processed1['星期'] = sale_data_processed1.apply(
    lambda r: date.fromisoformat(r['日期']).strftime("%w"), axis=1)

# sale_data_processed1['sal_last_day']=    for row in sale_data_processed1.iterrows()

# history_sale = pd.DataFrame(columns=['日期', 'last_day', 'last_2day', 'last_3day', 'last_7day'])
#
# sale_data_processed1['last_day'] = sale_data_processed1['销售数量']
# sale_data_processed1['last_2day'] = sale_data_processed1['销售数量']
# sale_data_processed1['last_3day'] = sale_data_processed1['销售数量']
# sale_data_processed1['last_7day'] = sale_data_processed1['销售数量']

history_sale_num = calc_history_data(sale_data_processed1)

history_sale_num.to_csv('./data/history_sale.csv', index=False)

# print('history sale num:', history_sale_num)

# print('before merge', sale_data_processed1)

history_sale_num['日期'] = history_sale_num['日期'].astype(str)
sale_data_processed1['日期'] = sale_data_processed1['日期'].astype(str)

# print('type:', sale_data_processed1.dtypes)

sale_data_processed1 = pd.merge(
    sale_data_processed1, history_sale_num, on='日期')

# sys.exit(0)

col_days = sale_data_processed1.apply(lambda r: (
    date.fromisoformat(r['日期']) - init_date).days, axis=1)

sale_data_processed1.insert(0, '天数', col_days)

sale_num = sale_data_processed1.pop('销售数量')
sale_data_processed1['销售数量'] = sale_num

sale_data_processed1.pop('商品编码')
sale_data_processed1.pop('销售额')
sale_data_processed1.pop('天气')
sale_data_processed1.pop('日期')

print(sale_data_processed1)

sale_data_processed1.columns = ['days', 'temp_hi', 'temp_lo', 'out',
                                'day_of_week', 'last_day', 'last_2day', 'last_3day', 'last_7day', 'sale_num']
#
sale_data_processed1.to_csv('./data/001488_pre1.csv', index=False)
